package com.baidu.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.baidu.constant.MessageConstant;
import com.baidu.entity.PageResult;
import com.baidu.entity.QueryPageBean;
import com.baidu.entity.Result;
import com.baidu.mapper.PermissionMapper;
import com.baidu.pojo.Permission;
import com.baidu.service.PermissionService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service(interfaceClass = PermissionService.class )
@Transactional
public class PermissionServiceImpl implements PermissionService {
	@Autowired
	private PermissionMapper permissionMapper;
/*
* page里装所有权限实体类
* */

	@Override
	public PageResult pageQuery(QueryPageBean queryPageBean) {
//开启分页
		PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());

		Page<Permission> page= permissionMapper.pageQuerybyCondition(queryPageBean.getQueryString());//该Page对象是分页助手帮助我们封住的对象。

		return new PageResult(page.getTotal(),page.getResult());
	}

	@Override
	public Result add(Permission permission) {
		//判断是否有重复的权限关键字
		int count= permissionMapper.findKeyWord(permission.getKeyword());
		if (count>0){
			return new Result(false,MessageConstant.ADD_PERMISSION_REP);

		}else {
			permissionMapper.add(permission);
			return new Result(true,MessageConstant.ADD_PERMISSION_SUCCESS);
		}



	}

	@Override
	public Result delete(Integer id) {

		//一个角色可以有多个权限，如果角色表有关联的，则不能删除，
//		先查询关联表，有无关联

		int count=permissionMapper.findRoleByPermissionID(id);
		if (count>0){
			return new Result(false, MessageConstant.DELETE_PERMISSION_FAIL);
		}else{

			permissionMapper.delete(id);
			return new Result(true,MessageConstant.DELETE_PERMISSION_SUCCESS);
		}


	}

	@Override
	public Permission findById(Integer id) {
		return permissionMapper.findById(id);
	}

	@Override
	public Result edit(Permission permission) {
		int count = permissionMapper.findKeyWord(permission.getKeyword());
		if (count>0){
			return new Result(false,"关键字重复");
		}else {
			permissionMapper.edit(permission);
			return 	 new Result(true,MessageConstant.EDIT_PERMISSION_SUCCESS);

		}


	}


    @Override
    public List<Permission> findPermission() {
        return permissionMapper.findPermission();
    }

    @Override
    public Integer[] findPermissionByRoleId(Integer id) {
        return permissionMapper.findPermissionByRoleId(id);
    }
}
